import { useState, useRef } from 'react';
import { request, useModel } from '@umijs/max';
import dayjs from 'dayjs'
import { Row, Col, Select, message, Input, Button, Space, Popconfirm, Form, Modal, DatePicker, InputNumber, Radio } from 'antd';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';
const { TextArea } = Input;

type TransferItem = {
  "createBy": string,
  "createTime": string,
  "updateBy": string,
  "updateTime": string,
  "remark": string,
  "id": number,
  "patentType": string,
  "number": string,
  "name": string,
  "filingTime": string,
  "empowerTime": string,
  "filingType": string,
  "caseType": string,
  "point": string,
  "amount": string,
  "userId": string,
  "flag": number,
  "status": string,
  "rickUserId": string,
  "nikeName": string
};

export default () => {
  const actionRef = useRef<ActionType>();
  const { initialState } = useModel("@@initialState");
  const dictData: any = initialState?.dictData;

  //新增转让相关
  const [form] = Form.useForm();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const onAdd = () => {
    form.resetFields();
    setIsModalOpen(true);
  }
  const handleOk = () => {
    form.validateFields()
      .then(async (values) => {
        values.filingTime = dayjs(values.filingTime).format('YYYY-MM-DD');
        values.empowerTime = dayjs(values.empowerTime).format('YYYY-MM-DD');
        await request(
          '/system/transferenceApiController',
          {
            method: values.id ? 'PUT' : 'POST',
            data: values
          }
        );
        setIsModalOpen(false);
        message.success(values.id ? '编辑成功' : '新增成功');
        actionRef.current?.reload();
      })
      .catch(() => {})
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  //编辑转让相关
  const onEdit = async (item: TransferItem) => {
    const { id} = item;
    const { data } = await request('/system/transferenceApiController/' + id);
    const { patentType, number, name, filingTime, empowerTime, filingType, caseType, point, amount, status }: TransferItem = data;
    form.setFieldsValue({
      id, patentType, number, name,
      filingTime: dayjs(filingTime),
      empowerTime: dayjs(empowerTime),
      filingType, caseType, point, amount, status
    });
    setIsModalOpen(true);
  }

  //删除转让相关
  const onDelete = async (item: TransferItem) => {
    const {id} = item;
    await request(
      '/system/transferenceApiController/remove?id=' + id,
      { method: 'DELETE' }
    );
    message.success('删除成功');
    actionRef.current?.reload();
  }

  const columns: ProColumns<TransferItem>[] = [
    {
      width: 130,
      title: '申请号',
      dataIndex: 'number',
      hideInSearch: true,
    },
    {
      title: '发明名称',
      dataIndex: 'name',
      ellipsis: true,
      copyable: true
    },
    {
      width: 100,
      title: '申请日',
      hideInSearch: true,
      dataIndex: 'filingTime',
    },
    {
      width: 80,
      title: '专利类型',
      dataIndex: 'patentType',
      valueType: 'select',
      fieldProps: {
        options: dictData['专利类型']
      },
    },
    {
      width: 100,
      title: '案件状态类型',
      dataIndex: 'status',
      valueType: 'select',
      fieldProps: {
        options: dictData['案件状态类型']
      },
    },
    {
      width: 80,
      title: '案件领域',
      dataIndex: 'caseType',
      valueType: 'select',
      fieldProps: {
        options: dictData['案件领域']
      },
    },
    {
      title: '摘要',
      dataIndex: 'point',
      ellipsis: true,      //是否自动缩略
      copyable: false,      //是否支持复制
      hideInSearch: true,  //在查询表单中不展示此项
    },
    {
      width: 120,
      title: '价格',
      dataIndex: 'amount',
      valueType: 'money',
    },
    {
      width: 90,
      title: '操作',
      key: 'action',
      hideInSearch: true,
      render: (_, record) => (
        <Space size="middle">
          <Button
            onClick={() => onEdit(record)}
            icon={<EditOutlined />}
            type="primary"
            size="small">

          </Button>
          <Popconfirm
            title="删除提示"
            description="确定删除该数据吗?"
            onConfirm={() => onDelete(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              disabled={record.flag === 0}
              icon={<DeleteOutlined />}
              type="primary"
              size="small"
              danger>
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<TransferItem>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={async (params) => {
          const {current, pageSize} = params;
          const params_ = {
            ...params,
            pageSize,
            pageNum: current,
          }
          delete params_.current;
          const result =  await request('/system/transferenceApiController/listUser', { method: 'GET', params: params_ });
          return {
            data: result?.rows,
            success: result?.code === 200,
            total: result?.total,
          }
        }}
        columnsState={{
          persistenceKey: 'transferTransactions-table',
          persistenceType: 'localStorage',
          defaultValue: {
            option: { fixed: 'right', disable: true },
          },
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          span: 6,
        }}
        options={{
          //菜单栏 options 配置
          fullScreen: true,
          density: true,
          setting: {
            draggable: true,
            checkable: true,
            checkedReset: true,
            listsHeight: 400,
          },
        }}
        pagination={{
          pageSize: 5,
          onChange: (page) => console.log(page),
        }}
        dateFormatter={false}
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={onAdd}
            type="primary"
          >
            新建
          </Button>
        ]}
      />
      <Modal
        title="新增转让"
        width={800}
        maskClosable={false}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}>
        <Form
          name="basic"
          form={form}
          labelCol={{
            span: 6,
          }}
          wrapperCol={{
            span: 18,
          }}
          initialValues={{
            id: "",
            patentType: "",
            number: "",
            name: "",
            filingTime: "",
            empowerTime: "",
            filingType: "",
            caseType: "",
            point: "",
            amount: "",
            status: "",
          }}
          autoComplete="off"
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="ID"
                name="id"
                hidden
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="申请号"
                name="number"
                rules={[
                  {
                    required: true,
                    message: '请输入申请号!',
                  },
                ]}
              >
                <Input maxLength={13} showCount={true}/>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="发明名称"
                name="name"
                rules={[
                  {
                    required: true,
                    message: '请输入发明名称!',
                  },
                ]}
              >
                <Input maxLength={30} showCount={true} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="申请日"
                name="filingTime"
                rules={[
                  {
                    required: true,
                    message: '请输入申请日!',
                  },
                ]}
              >
                <DatePicker style={{width: '100%'}} format='YYYY-MM-DD' />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="专利类型"
                name="patentType"
              >
                <Select options={dictData['专利类型']} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="案件状态类型"
                name="status"
              >
                <Select options={dictData['案件状态类型']} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="案件领域"
                name="caseType"
              >
                <Select options={dictData['案件领域']} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="申请人类型"
                name="filingType"
              >
                <Select options={dictData['申请人类型']} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="价格"
                name="amount"
              >
                <InputNumber
                  prefix="￥"
                  style={{width: '100%'}}
                  controls={true} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="授权日"
                name="empowerTime"
                rules={[
                  {
                    required: true,
                    message: '请输入授权日!',
                  },
                ]}
              >
                <DatePicker style={{width: '100%'}} format='YYYY-MM-DD' />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                label="简要"
                name="point"
                labelCol={{
                  span: 3,
                }}
                wrapperCol={{
                  span: 21,
                }}
              >
                <TextArea maxLength={300} showCount={true} rows={4} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </PageContainer>
  );
};
